import { getUploadSinature } from '@/network/apis';
import { router, storage, toast } from '@/utils';
import Taro from '@tarojs/taro';

export const randomFileName = () => {
	// 时间戳+随机4位数
	return Date.now() + Math.floor(Math.random() * 10000);
};

export const chooseFileFromAlbum = async () => {
	return new Promise((resolve, reject) => {
		wx.chooseMedia({
			count: 1,
			mediaType: ['image', 'video'],
			sourceType: ['album'],
			maxDuration: 60,
			success: async res => {
				return resolve(res);
			}
		});
	});
};

export const chooseFileFromCamera = async () => {
	return new Promise((resolve, reject) => {
		wx.chooseMedia({
			count: 1,
			mediaType: ['image', 'video'],
			sourceType: ['camera'],
			maxDuration: 60,
			success: async res => {
				return resolve(res);
			}
		});
	});
};

/**
 *
 * @param {*} type
 * @returns
 */
export const chooseFileFromMessage = async (options = null) => {
	const { type, count } = options || {};

	const chooseOptions = { count: count || 1, type: type || 'all' }; // count: 选择文件的数量, type: 选择文件的类型 all: 所有文件, image: 图片 video: 视频

	return new Promise((resolve, reject) => {
		wx.chooseMessageFile({
			...chooseOptions,
			success: async res => {
				return resolve(res);
			},
			fail: err => {
				// uni.showToast({ duration: 5000, title: '选择文件失败，ERR:' + JSON.stringify(err) });
			}
		});
	});
};

export const uploadFile = async (options = null) => {
	const { file, props, useOriginalFileName } = options || {};

	if (!file) {
		toast.error('文件不存在');
		return;
	}

	const sinatureOption = await getSinatureOfUploader({ dir: props.key, companyId: storage.get('manufacturerId') });
	const key = `${useOriginalFileName ? file.name : randomFileName() + '.' + file.extname}`;

	const formData = {
		key: sinatureOption.dir + key,
		policy: sinatureOption.policy,
		signature: sinatureOption.signature,
		OSSAccessKeyId: sinatureOption.accessid
	};

	return new Promise((resolve, reject) => {
		console.log('formData', formData);

		Taro.showLoading({
			title: '上传中...'
		});

		Taro.uploadFile({
			url: sinatureOption.host,
			filePath: file.path,
			name: 'file',
			formData: formData,
			timeout: 60 * 1000, // 60秒
			success: res => {
				console.log('res', res);
				if (res.statusCode === 204) {
					return resolve({ filename: key, filepath: sinatureOption.host + '/' + sinatureOption.dir + key });
				} else {
					toast.error('文件上传失败');
				}
			},
			fail: err => {
				toast.error('文件上传失败，ERR:' + JSON.stringify(err));
			},
			complete: () => {
				Taro.hideLoading();
			}
		});
	});
};

export const getSinatureOfUploader = options => {
	return new Promise(async (resolve, reject) => {
		// const timestamp = Date.parse(new Date()) / 1000;
		// const sinatureLocal = uni.getStorageSync('UPLOAD_SINATURE') ? JSON.parse(uni.getStorageSync('UPLOAD_SINATURE')) : null;
		// const { expire, sinature } = sinatureLocal || {};

		// if (!expire || !sinature || timestamp > expire) {
		// 	uni.removeStorageSync('UPLOAD_SINATURE');

		// 	const { data, ret } = await getUploadSinature(options);

		// 	if (ret !== 0) {
		// 		uni.showToast({ title: '获取签名失败' });
		// 		return;
		// 	}

		// 	uni.setStorageSync('UPLOAD_SINATURE', JSON.stringify(data));
		// 	return resolve(data);
		// }

		// return resolve(sinatureLocal);

		const { data, ret } = await getUploadSinature(options);

		if (ret !== 0) {
			toast.error('获取签名失败');
			return;
		}

		return resolve(data);
	});
};

export const previewFile = url => {
	Taro.downloadFile({
		url: url,
		success: function (res) {
			const filePath = res.tempFilePath;
			Taro.openDocument({
				filePath: filePath,
				success: function (res) {
					console.log('打开文档成功');
				}
			});
		},
		fail: function (res) {
			toast.error('文件预览失败');
		}
	});
};

export const shareFile = url => {
	wx.downloadFile({
		url: url, // 下载url
		success(res) {
			console.log('🚀 ~ success ~ res:', res);
			wx.shareFileMessage({
				filePath: res.tempFilePath,
				success() {},
				fail: console.error
			});
		},
		fail: console.error
	});
};
